package mc.support.task.common;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Created with IntelliJ IDEA. <br/>
 * Author: Francis Yun    <br/>
 * Date: 2014-05-03  <br/>
 */
public abstract class Worker
        extends CronTaskAdaptor
        implements MultiRunnable, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public synchronized void processInjection(Object target) {
        AutowireCapableBeanFactory acb = applicationContext.getAutowireCapableBeanFactory();
        AutowiredAnnotationBeanPostProcessor autowiredProcessor = new AutowiredAnnotationBeanPostProcessor();
        autowiredProcessor.setBeanFactory( acb );
        autowiredProcessor.processInjection( target );
    }

    @Override
    public Runnable copySelf() {
        Worker worker;
        try {
            Constructor<? extends Worker> constructor = this.getClass().getConstructor();
            worker = constructor.newInstance();
            processInjection( worker );
        } catch (NoSuchMethodException | InvocationTargetException
                | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException( "MultiRunnable self copy fail!", e );
        }
        return worker;
    }

    @Override
    public boolean isLaunchNow() {
        return true;
    }

    @Override
    public boolean needsSchedule() {
        return false;
    }

    @Override
    public String getCronPattern() {
        return null;
    }

}
